import axios from "axios";
import { getToken, isLogin } from "../utils/Token";
import FileSaver from "file-saver";
const { saveAs } = FileSaver;

class HttpRequest {
  async request(url: string, method: string, data: any, options: any = {}) {
    const sendUrl =
      url.startsWith("http://") || url.startsWith("https://")
        ? url
        : `/travel${url}`;
    const token = getToken();
    if (token) {
      options.headers = options.headers || {};
      options.headers.Authorization = "Bearer " + token;
    }
    return axios({
      url: sendUrl,
      method,
      data: method === "POST" || method === "PUT" ? data : undefined, // 仅 POST 和 PUT 有 body
      params: method === "GET" || method === "DELETE" ? data : undefined, // GET 和 DELETE 使用 params
      ...options,
    })
      .then((response) => {
        if (response.data) {
          if (
            response.data.code === 200 ||
            response.data.type ==
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          ) {
            return response.data;
          } else if (response.data.code === 401) {
            isLogin.set("");
          }
        }
        return Promise.reject(response.data);
      })
      .catch((error) => {
        return Promise.reject(error);
      });
  }

  GET(url: string, params: any, options: any) {
    return this.request(url, "GET", params, options);
  }

  POST(url: string, data: any, options: any) {
    return this.request(url, "POST", data, options);
  }

  DOWNLOAD(url: string, params = {}, filename: string) {
    return this.POST(url, params, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
      .then(async (data) => {
        const isBlob = blobValidate(data);
        console.info("isBlob", isBlob, filename);
        if (isBlob) {
          const blob = new Blob([data]);
          saveAs(blob, filename);
        } else {
          const resText = await data.text();
          const rspObj = JSON.parse(resText);
          const errMsg = rspObj.msg;
          // ElMessage({
          //   message: errMsg,
          //   type: "error",
          // });
        }
      })
      .catch((r) => {
        console.error(r);
        // ElMessage({
        //   message: "下载文件出现错误(Error downloading file)!",
        //   type: "error",
        // });
      });
  }
}

function blobValidate(data) {
  return data.type !== "application/json";
}

export default new HttpRequest();
